# -*- coding: utf-8 -*-

from odoo import models, fields, api,_
from odoo.tools import float_compare
from datetime import datetime,timedelta
from odoo.exceptions import UserError, AccessError, ValidationError
from odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT
class PurchaseOrder(models.Model):
    _name = 'purchase.order'
    _inherit = ['purchase.order', 'base.approve']
    ref=fields.Char(related='partner_id.ref')
    planned_date_new = fields.Date(string=u'计划交期')
    # tax_id=fields.Many2one('account.tax',domain=[('type_tax_use','=','purchase')])

    approval_record_ids = fields.One2many('approval.records', 'res_id',
                                          domain=[('res_model', '=', 'purchase.order')])
    approve_flow_ids = fields.One2many('approve.flow', 'res_id', domain=[('res_model', '=', 'purchase.order')])

    @api.model
    def _default_notes(self):
        return self.env.user.company_id.purchase_note

    notes = fields.Text('Terms and conditions', default=_default_notes)
    def update_sequence(self):
        index = 1
        for line in self.order_line:
            line.item = index
            index = index + 1


    def update_sequencesss(self):
        lines=self.env[self._name].search([])
        for line in lines:
            line.update_sequence()

    def button_approve(self,force=False):
        super(PurchaseOrder, self).button_approve(force=force)
        self.update_sequence()




    product_count=fields.Float(compute='get_product_count')
    def get_product_count(self):
        for order in self:
            count = 0.0
            for line in order.order_line:
                count += line.product_qty
            order.product_count = count

    @api.onchange('partner_id')
    def onchange_partner_id_for_sheet_user(self):
        if not self.user_id:
            self.user_id=self.partner_id.user_id
    @api.onchange('tax_id')
    def onchange_tax_id_11(self):
        for line in self.order_line:
            line.taxes_id = [(6, 0, [self.tax_id.id])]



    state = fields.Selection([
        ('draft', u'草稿'),
        ('sent', u'發送詢價單'),
        ('to approve', u'审核中'),
        ('rejected', u'拒绝'),
        ('purchase', u'采购订单'),
        ('done', u'已完成'),
        ('cancel', u'已取消'),
    ], default='draft', track_visibility='onchange')

    def get_default_department_id(self):
        if self.env.user.employee_ids:
            return self.env.user.employee_ids[0].department_id.id

    department_id = fields.Many2one('hr.department', ondelete='restrict', string='部门',
                                    default=get_default_department_id)

    def action_approve_done(self, remark=''):
        super(PurchaseOrder, self).action_approve_done()
        if remark:
            reject_str = "備註：" + remark
            self.message_post(reject_str)
        self.button_approve(force=False)

    def check_values(self):
        self.order_line.validate_the_price_unit()
        super(PurchaseOrder, self).check_values()
        if not self.order_line:
            raise UserError(u'請添加採購明細')






class PurchaseOrderLine(models.Model):
    _inherit = 'purchase.order.line'
    remark=fields.Char(string=u'备注')
    item=fields.Integer(string=u'项次')
    payment_term_id=fields.Many2one('account.payment.term',related='order_id.payment_term_id',readonly=True,string='付款条款')
    user_id = fields.Many2one('res.users', related='order_id.user_id', readonly=True,string=u'采购员')
    default_code = fields.Char( related='product_id.default_code', readonly=True, string=u'料号')
    planned_date_new=fields.Date(related='order_id.planned_date_new', readonly=True,string=u'计划交期')
    state = fields.Selection([
        ('draft', u'草稿'),
        ('sent', u'發送詢價單'),
        ('to approve', u'审核中'),
        ('rejected', u'拒绝'),
        ('purchase', u'采购订单'),
        ('done', u'已完成'),
        ('cancel', u'已取消'),
    ], related='order_id.state',store=True)
    to_receive_qty=fields.Float(compute='compute_to_receive_qty',string=u'未交量')
    received_amount=fields.Float(compute='compute_receive_amount',string=u'交货含税金额')
    received_date=fields.Char(compute='compute_received_date',string=u'入库日期')
    shipping_info=fields.Char(compute='compute_shipping_info',string=u'入库单号')
    def compute_shipping_info(self):
        for line in self:
            if line.move_ids:
                picking_ids=line.move_ids.filtered(lambda x:x.state!='cancel').mapped('picking_id')
                line.shipping_info=';'.join(p.name for p in picking_ids)
            else:
                line.shipping_info=''


    def compute_received_date(self):
        for line in self:
            line.received_date = ''
            picking_ids=line.move_ids.filtered(lambda x:x.state=='done').mapped('picking_id')
            if picking_ids:
                received_date= ';'.join(
                    (p.date + timedelta(hours=8)).strftime(
                        DEFAULT_SERVER_DATETIME_FORMAT) for p in picking_ids)
                line.received_date=received_date

    def compute_receive_amount(self):
        for line in self:
            line.received_amount=line.price_unit_1*line.qty_received

    @api.depends()
    def compute_to_receive_qty(self):
        for line in self:
            if line.order_id.state not in ['purchase', 'done']:
                line.to_receive_qty = 0.0
            if line.product_id.type not in ['consu', 'product']:
                line.to_receive_qty = 0.0
            total = 0.0
            for move in line.move_ids:
                if move.state not in ['done', 'cancel']:
                    if move.product_uom != line.product_uom:
                        total += move.product_uom._compute_quantity(move.product_uom_qty, line.product_uom)
                    else:
                        total += move.product_uom_qty
            line.to_receive_qty = total



    price_unit_1=fields.Float(compute='compute_price_unit_1',string=u'未税单价')
    price_unit_2 = fields.Float(compute='compute_price_unit_1',string=u'含税单价')
    @api.depends('product_uom_qty','price_subtotal','price_total')
    def compute_price_unit_1(self):
        for line in self:
            if line.product_uom_qty>0:
                line.price_unit_1=line.price_subtotal/line.product_uom_qty
                line.price_unit_2 = line.price_total / line.product_uom_qty



    @api.constrains('taxes_id')
    def _check_tax_id(self):
        if self.taxes_id and len(self.taxes_id)>1:
            raise ValidationError(_('税率不能超过1个'))


    def get_the_price(self):
        line_id=self.env['purchase.pricing.order.line'].search([('product_id','=',self.product_id.id),('partner_id','=',self.partner_id.id),('state','=','done')],order='new_date desc',limit=1)

        if line_id:
            return line_id.price_unit
        else:
            raise UserError('未找到对应核价单')

    description = fields.Char(string=u'规格')

    @api.onchange('product_id')
    def onchange_product_id_for_des(self):
        if not self.product_id:
            self.description = ''
        else:
            self.description = self.product_id.description

    def validate_the_price_unit(self):
        for r in self:
            if r.get_the_price():
                if float_compare(r.get_the_price(),r.price_unit,precision_digits=2)!=0:
                    raise UserError('与核价单价格不一致，请核对')



    @api.onchange('product_id')
    def onchange_product_id(self):
        if not self.product_id:
            return

        # Reset date, price and quantity since _onchange_quantity will provide default values
        self.date_planned = datetime.today().strftime(DEFAULT_SERVER_DATETIME_FORMAT)
        self.price_unit = self.product_qty = 0.0
        if self.order_id.partner_id.tax_id:
            self.taxes_id = self.order_id.partner_id.tax_id

        if self.get_the_price():
            self.price_unit=self.get_the_price()

        self._product_id_change()

        self._suggest_quantity()
        self._onchange_quantity()

    def _compute_tax_id(self):
        for line in self:

            line.taxes_id = self.order_id.partner_id.tax_id

    @api.onchange('product_qty', 'product_uom')
    def _onchange_quantity(self):
        pass


